// 任务数据存储
let tasks = [];
let taskIdCounter = 1;
let quadrantFocusEnabled = false;
let quadrantFocusSuspended = false;
let currentModalMode = 'add';
let editingTaskId = null;

const QUADRANT_FOCUS_STORAGE_KEY = 'quadrant-focus-enabled';
const QUADRANT_TYPES = [
    'urgent-important',
    'important-not-urgent',
    'not-important-urgent',
    'not-important-not-urgent'
];

const quadrantFilterState = QUADRANT_TYPES.reduce((acc, quadrant) => {
    acc[quadrant] = 'all';
    return acc;
}, {});

const dropZoneSortables = {};

// ================== 拖拽状态管理器 ==================

/**
 * 拖拽状态管理器 - 负责处理所有拖拽相关的状态清理
 */
class DragStateManager {
    // 跟踪所有拖拽相关的CSS类
    static DRAG_CLASSES = [
        'dragging', 'drag-over', 'sortable-chosen', 
        'sortable-ghost', 'sortable-drag',
        'fullscreen-sortable-chosen', 'fullscreen-sortable-ghost', 
        'fullscreen-sortable-drag', 'drag-active'
    ];
    
    /**
     * 清理所有拖拽状态
     * @param {boolean} forceCleanup 是否强制清理（包括document级别）
     */
    static clearAllDragStates(forceCleanup = false) {
        try {
            const selector = forceCleanup ? '*' : '.task, .fullscreen-task, .drop-zone, .fullscreen-tasks';
            const elements = document.querySelectorAll(selector);
            
            elements.forEach(element => {
                this.DRAG_CLASSES.forEach(className => {
                    if (element.classList.contains(className)) {
                        element.classList.remove(className);
                        console.log(`已清理拖拽状态类: ${className} from`, element);
                    }
                });
                
                // 清理focus状态
                if (element.tagName === 'DIV' && (element.classList.contains('task') || element.classList.contains('fullscreen-task'))) {
                    element.blur();
                }
            });
            
            // 强制重绘确保样式更新
            document.body.offsetHeight;
            
            console.log('拖拽状态清理完成');
            
        } catch (error) {
            console.error('清理拖拽状态时发生错误:', error);
        }
    }
    
    /**
     * 检查是否存在残留的拖拽状态
     * @returns {boolean} 是否存在残留状态
     */
    static hasRemainingDragStates() {
        return this.DRAG_CLASSES.some(className => {
            return document.querySelector(`.${className}`) !== null;
        });
    }
    
    /**
     * 验证拖拽状态清理是否完整
     * @returns {Object} 验证结果
     */
    static validateDragStateClean() {
        const remainingStates = [];
        
        this.DRAG_CLASSES.forEach(className => {
            const elements = document.querySelectorAll(`.${className}`);
            if (elements.length > 0) {
                remainingStates.push({
                    className,
                    count: elements.length,
                    elements: Array.from(elements)
                });
            }
        });
        
        const isClean = remainingStates.length === 0;
        
        if (!isClean) {
            console.warn('检测到残留的拖拽状态:', remainingStates);
        }
        
        return {
            isClean,
            remainingStates
        };
    }
    
    /**
     * 自动修复拖拽状态
     */
    static autoFixDragStates() {
        const validation = this.validateDragStateClean();
        if (!validation.isClean) {
            console.log('执行自动修复拖拽状态');
            this.clearAllDragStates(true);
            
            // 延迟验证修复结果
            setTimeout(() => {
                const recheck = this.validateDragStateClean();
                if (recheck.isClean) {
                    console.log('✅ 拖拽状态修复成功');
                } else {
                    console.error('❌ 拖拽状态修复失败:', recheck.remainingStates);
                }
            }, 100);
        }
        
        return validation.isClean;
    }
    
    /**
     * 设置拖拽状态监控
     */
    static setupDragStateMonitoring() {
        // 定期检查拖拽状态
        setInterval(() => {
            if (this.hasRemainingDragStates()) {
                console.warn('定期检查发现残留拖拽状态，执行清理');
                this.clearAllDragStates();
            }
        }, 5000); // 每5秒检查一次
        
        console.log('拖拽状态监控已启动');
    }
}

/**
 * 保存任务数据到localStorage
 */
function saveTasksToLocalStorage() {
    const data = {
        tasks: tasks,
        taskIdCounter: taskIdCounter
    };
    localStorage.setItem('quadrant-todo-data', JSON.stringify(data));
}

/**
 * 从localStorage加载任务数据
 */
function loadTasksFromLocalStorage() {
    const savedData = localStorage.getItem('quadrant-todo-data');
    if (savedData) {
        try {
            const data = JSON.parse(savedData);
            tasks = data.tasks || [];
            taskIdCounter = data.taskIdCounter || 1;
            
            // 为没有 order 字段的任务分配顺序（向后兼容）
            tasks.forEach(task => {
                if (task.order === undefined) {
                    const quadrantTasks = tasks.filter(t => t.quadrant === task.quadrant && t.order !== undefined);
                    task.order = quadrantTasks.length;
                }
            });
        } catch (error) {
            console.error('加载本地存储数据失败:', error);
            tasks = [];
            taskIdCounter = 1;
        }
    }
}

/**
 * 添加新任务
 */
function addTask() {
    const title = document.getElementById('taskTitle').value.trim();
    const description = document.getElementById('taskDescription').value.trim();
    const quadrant = document.getElementById('taskQuadrant').value;

    if (!title) {
        alert('请输入任务标题');
        return;
    }

    const task = {
        id: taskIdCounter++,
        title: title,
        description: description,
        quadrant: quadrant,
        completed: false,
        createdAt: new Date().toLocaleString(),
        order: tasks.filter(t => t.quadrant === quadrant).length
    };

    tasks.push(task);
    refreshQuadrant(quadrant);
    clearForm();
    saveTasksToLocalStorage();
}

/**
 * 打开添加任务弹窗
 * @param {string} presetQuadrant 预设的象限类型（可选）
 */
function openAddTaskModal(presetQuadrant = null, options = {}) {
    const { mode = 'add', task = null } = options;
    currentModalMode = mode;
    editingTaskId = mode === 'edit' && task ? task.id : null;

    const modal = document.getElementById('addTaskModal');
    const titleInput = document.getElementById('modalTaskTitle');
    const descriptionInput = document.getElementById('modalTaskDescription');
    const quadrantSelect = document.getElementById('modalTaskQuadrant');
    const stayOpenToggle = document.getElementById('modalStayOpen');
    const stayOpenGroup = document.querySelector('.stay-open-group');
    const modalTitle = modal.querySelector('.modal-title');
    const primaryButton = document.getElementById('modalPrimaryButton');

    if (mode === 'edit' && task) {
        titleInput.value = task.title;
        descriptionInput.value = task.description || '';
        quadrantSelect.value = task.quadrant;
        if (stayOpenToggle) {
            stayOpenToggle.checked = false;
        }
        if (stayOpenGroup) {
            stayOpenGroup.style.display = 'none';
        }
        modalTitle.textContent = '编辑任务';
        if (primaryButton) {
            primaryButton.textContent = '保存修改';
        }
    } else {
        currentModalMode = 'add';
        editingTaskId = null;
        clearModalForm();
        if (presetQuadrant) {
            quadrantSelect.value = presetQuadrant;
        }
        if (stayOpenGroup) {
            stayOpenGroup.style.display = 'flex';
        }
        modalTitle.textContent = '添加新任务';
        if (primaryButton) {
            primaryButton.textContent = '添加任务';
        }
    }

    modal.classList.add('show');

    setTimeout(() => {
        titleInput.focus();
        titleInput.select();
    }, 100);
}

/**
 * 关闭添加任务弹窗
 */
function closeAddTaskModal() {
    const modal = document.getElementById('addTaskModal');
    modal.classList.remove('show');
    clearModalForm();

    currentModalMode = 'add';
    editingTaskId = null;

    const stayOpenGroup = document.querySelector('.stay-open-group');
    if (stayOpenGroup) {
        stayOpenGroup.style.display = 'flex';
    }

    const modalTitle = modal.querySelector('.modal-title');
    if (modalTitle) {
        modalTitle.textContent = '添加新任务';
    }

    const primaryButton = document.getElementById('modalPrimaryButton');
    if (primaryButton) {
        primaryButton.textContent = '添加任务';
    }
}

/**
 * 从弹窗添加任务
 */
function addTaskFromModal() {
    const title = document.getElementById('modalTaskTitle').value.trim();
    const description = document.getElementById('modalTaskDescription').value.trim();
    const quadrant = document.getElementById('modalTaskQuadrant').value;
    const stayOpenToggle = document.getElementById('modalStayOpen');
    const stayOpen = stayOpenToggle ? stayOpenToggle.checked : false;
    const isEditMode = currentModalMode === 'edit' && editingTaskId !== null;

    if (!title) {
        alert('请输入任务标题');
        document.getElementById('modalTaskTitle').focus();
        return;
    }

    if (isEditMode) {
        const task = tasks.find(t => t.id === editingTaskId);
        if (!task) {
            closeAddTaskModal();
            showToast('未找到任务，编辑已取消', 2000);
            return;
        }

        const previousQuadrant = task.quadrant;

        task.title = title;
        task.description = description;
        task.quadrant = quadrant;

        if (previousQuadrant !== quadrant) {
            reorderTasks(previousQuadrant);
            task.order = tasks.filter(t => t.quadrant === quadrant && t.id !== task.id).length;
            reorderTasks(quadrant);
        }

        saveTasksToLocalStorage();
        refreshAllTasks();
        closeAddTaskModal();
        showToast('任务已更新', 2000);
        return;
    }

    const task = {
        id: taskIdCounter++,
        title: title,
        description: description,
        quadrant: quadrant,
        completed: false,
        createdAt: new Date().toLocaleString(),
        order: tasks.filter(t => t.quadrant === quadrant).length
    };

    tasks.push(task);
    refreshQuadrant(quadrant);
    saveTasksToLocalStorage();

    if (stayOpen) {
        resetModalForContinuousAdd();
        showToast('任务已保存，可继续新增');
    } else {
        closeAddTaskModal();
    }
}

/**
 * 清空弹窗表单
 */
function clearModalForm() {
    document.getElementById('modalTaskTitle').value = '';
    document.getElementById('modalTaskDescription').value = '';
    document.getElementById('modalTaskQuadrant').value = 'urgent-important';

    const stayOpenToggle = document.getElementById('modalStayOpen');
    if (stayOpenToggle) {
        stayOpenToggle.checked = false;
    }
}

/**
 * 准备继续新增任务（保持弹窗开启）
 */
function resetModalForContinuousAdd() {
    document.getElementById('modalTaskTitle').value = '';
    document.getElementById('modalTaskDescription').value = '';

    setTimeout(() => {
        document.getElementById('modalTaskTitle').focus();
    }, 50);
}

/**
 * 显示全局提示
 * @param {string} message 提示文本
 * @param {number} [duration=2200] 显示时长（毫秒）
 */
function showToast(message, duration = 2200) {
    const container = document.getElementById('toastContainer');
    if (!container) {
        return;
    }

    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.textContent = message;
    container.appendChild(toast);

    requestAnimationFrame(() => {
        toast.classList.add('visible');
    });

    const hideDelay = Math.max(600, duration - 250);

    setTimeout(() => {
        toast.classList.remove('visible');
    }, hideDelay);

    setTimeout(() => {
        toast.remove();
    }, Math.max(duration, hideDelay + 300));
}

/**
 * 切换任务完成状态
 */
function toggleComplete(taskId) {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
        task.completed = !task.completed;
        refreshAllTasks();
        saveTasksToLocalStorage(); // 保存到localStorage
    }
}

/**
 * 删除任务
 */
function deleteTask(taskId) {
    if (confirm('确定要删除这个任务吗？')) {
        tasks = tasks.filter(t => t.id !== taskId);
        refreshAllTasks();
        saveTasksToLocalStorage(); // 保存到localStorage
    }
}

/**
 * 拖拽放下处理
 */
function handleDrop(e) {
    e.preventDefault();
    e.target.classList.remove('drag-over');
    
    const taskId = parseInt(e.dataTransfer.getData('text/plain'));
    const newQuadrant = e.target.closest('.quadrant').dataset.quadrant;
    
    const task = tasks.find(t => t.id === taskId);
    if (task && task.quadrant !== newQuadrant) {
        task.quadrant = newQuadrant;
        refreshAllTasks();
        saveTasksToLocalStorage(); // 保存到localStorage
    }
}

/**
 * 添加一些示例任务
 */
function addSampleTasks() {
    // 只有在没有本地数据时才添加示例任务
    if (tasks.length === 0) {
        const sampleTasks = [
            {
                title: '完成项目报告',
                description: '准备下周一的项目进度报告',
                quadrant: 'urgent-important'
            },
            {
                title: '学习新技术',
                description: '学习React框架的基础知识',
                quadrant: 'important-not-urgent'
            },
            {
                title: '回复邮件',
                description: '回复客户的咨询邮件',
                quadrant: 'not-important-urgent'
            },
            {
                title: '整理桌面',
                description: '清理办公桌上的文件',
                quadrant: 'not-important-not-urgent'
            }
        ];

        sampleTasks.forEach(sampleTask => {
            const task = {
                id: taskIdCounter++,
                title: sampleTask.title,
                description: sampleTask.description,
                quadrant: sampleTask.quadrant,
                completed: false,
                createdAt: new Date().toLocaleString(),
                order: sampleTasks.indexOf(sampleTask)
            };
            tasks.push(task);
        });

        refreshAllTasks();
        saveTasksToLocalStorage(); // 保存示例任务
    }
}

/**
 * 初始化快捷新增按钮事件
 */
function initQuickAddButtons() {
    const quickAddButtons = document.querySelectorAll('.quick-add-btn');
    
    quickAddButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const quadrantType = this.dataset.quadrant;
            openAddTaskModal(quadrantType);
        });
    });
}

/**
 * 初始化象限放大按钮
 */
function initQuadrantExpandButtons() {
    const expandButtons = document.querySelectorAll('.quadrant-expand-btn');

    expandButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const quadrantType = this.dataset.quadrant;
            if (quadrantType) {
                openFullscreenModal(quadrantType);
            }
        });
    });
}

function initExportModalButtons() {
    const exportButton = document.getElementById('exportConfirmButton');
    if (exportButton) {
        exportButton.addEventListener('click', exportTasks);
    }

    const cancelButton = document.getElementById('exportCancelButton');
    if (cancelButton) {
        cancelButton.addEventListener('click', closeExportModal);
    }
}

/**
 * 隐藏新增按钮
 */
function hideAddTaskButton() {
    const addBtn = document.querySelector('.add-task-trigger');
    if (addBtn) {
        addBtn.classList.add('hidden');
    }
}

/**
 * 重新定位导出按钮
 */
function repositionExportButton() {
    const exportBtn = document.querySelector('.export-task-trigger');
    if (exportBtn) {
        exportBtn.classList.add('repositioned');
    }
}

/**
 * 初始化按钮配置
 */
function initButtonConfiguration() {
    // 隐藏新增按钮
    hideAddTaskButton();
    
    // 重新定位导出按钮
    repositionExportButton();
}

/**
 * 清理所有象限的聚焦样式
 */
function clearQuadrantFocusState() {
    const quadrantsContainer = document.querySelector('.quadrants');
    if (!quadrantsContainer) {
        return;
    }

    quadrantsContainer.removeAttribute('data-active-quadrant');

    document.querySelectorAll('.quadrant').forEach(element => {
        element.classList.remove('focus-active', 'focus-inactive');
    });
}

/**
 * 临时暂停象限聚焦（例如拖拽时）
 */
function suspendQuadrantFocus() {
    if (quadrantFocusSuspended) {
        return;
    }

    quadrantFocusSuspended = true;
    clearQuadrantFocusState();

    const quadrantsContainer = document.querySelector('.quadrants');
    if (quadrantsContainer) {
        quadrantsContainer.classList.add('focus-suspended');
    }
}

/**
 * 恢复象限聚焦
 */
function resumeQuadrantFocus() {
    if (!quadrantFocusSuspended) {
        return;
    }

    quadrantFocusSuspended = false;

    const quadrantsContainer = document.querySelector('.quadrants');
    if (!quadrantsContainer) {
        return;
    }

    quadrantsContainer.classList.remove('focus-suspended');

    if (!quadrantFocusEnabled) {
        return;
    }

    const hoveredQuadrant = quadrantsContainer.querySelector('.quadrant:hover');
    if (hoveredQuadrant) {
        applyQuadrantFocus(hoveredQuadrant);
    }
}

/**
 * 设置象限聚焦模式状态
 * @param {boolean} enabled 是否启用聚焦模式
 */
function setQuadrantFocusEnabled(enabled) {
    quadrantFocusEnabled = enabled;
    const quadrantsContainer = document.querySelector('.quadrants');
    if (!quadrantsContainer) {
        return;
    }

    clearQuadrantFocusState();
    quadrantsContainer.classList.toggle('focus-enabled', enabled);

    if (!enabled) {
        quadrantFocusSuspended = false;
        quadrantsContainer.classList.remove('focus-suspended');
    }
}

/**
 * 将聚焦样式应用到指定象限
 * @param {HTMLElement} quadrantElement 需要聚焦的象限元素
 */
function applyQuadrantFocus(quadrantElement) {
    if (!quadrantFocusEnabled || quadrantFocusSuspended || !quadrantElement) {
        return;
    }

    const quadrantsContainer = document.querySelector('.quadrants');
    if (!quadrantsContainer) {
        return;
    }

    const quadrants = document.querySelectorAll('.quadrant');
    quadrantsContainer.dataset.activeQuadrant = quadrantElement.dataset.quadrant || '';

    quadrants.forEach(element => {
        const isActive = element === quadrantElement;
        element.classList.toggle('focus-active', isActive);
        element.classList.toggle('focus-inactive', !isActive);
    });
}

/**
 * 初始化象限聚焦模式开关和相关交互
 */
function initQuadrantFocusToggle() {
    const toggle = document.getElementById('quadrantFocusToggle');
    const quadrantsContainer = document.querySelector('.quadrants');
    const quadrants = document.querySelectorAll('.quadrant');

    if (!toggle || !quadrantsContainer || quadrants.length === 0) {
        return;
    }

    let savedPreference = null;
    try {
        savedPreference = localStorage.getItem(QUADRANT_FOCUS_STORAGE_KEY);
    } catch (error) {
        console.warn('读取象限聚焦偏好失败:', error);
    }

    const shouldEnable = savedPreference === 'true';
    toggle.checked = shouldEnable;
    setQuadrantFocusEnabled(shouldEnable);

    toggle.addEventListener('change', () => {
        const enabled = toggle.checked;
        setQuadrantFocusEnabled(enabled);
        try {
            localStorage.setItem(QUADRANT_FOCUS_STORAGE_KEY, enabled ? 'true' : 'false');
        } catch (error) {
            console.warn('保存象限聚焦偏好失败:', error);
        }
    });

    quadrants.forEach(quadrant => {
        quadrant.addEventListener('mouseenter', () => {
            if (!quadrantFocusEnabled || quadrantFocusSuspended) {
                return;
            }
            applyQuadrantFocus(quadrant);
        });
    });

    quadrantsContainer.addEventListener('mouseleave', () => {
        if (!quadrantFocusEnabled || quadrantFocusSuspended) {
            return;
        }
        clearQuadrantFocusState();
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化全局错误处理
    initGlobalErrorHandling();
    
    // 初始化拖拽状态管理
    initDragStateManagement();
    
    // 初始化按钮配置（隐藏新增按钮、重新定位导出按钮）
    initButtonConfiguration();

    // 初始化象限聚焦开关
    initQuadrantFocusToggle();
    
    // 优先从mongoStorage加载数据
    loadTasksFromLocalStorage();
    
    // 数据完整性校验
    const validation = validateAllTasksData();
    if (!validation.isValid) {
        console.warn('检测到数据问题:', validation);
        if (repairTasksData()) {
            console.log('数据问题已修复');
        }
    }
    
    // 立即渲染已加载的任务
    refreshAllTasks();
    
    initDropZones();
    
    // 只有在没有数据时才添加示例任务
    if (tasks.length === 0) {
        addSampleTasks();
    }
    
    // 键盘事件监听
    setupKeyboardEvents();
    
    // 初始化象限标题的双击事件
    initQuadrantDoubleClick();
    
    // 初始化快捷新增按钮
    initQuickAddButtons();

    // 初始化象限放大按钮
    initQuadrantExpandButtons();

    // 初始化象限过滤按钮
    initQuadrantFilters();

    // 初始化导出弹窗按钮
    initExportModalButtons();

    console.log('应用初始化完成，已加载', tasks.length, '个任务');
});

/**
 * 初始化象限标题的双击事件
 */
function initQuadrantDoubleClick() {
    const quadrantTitles = document.querySelectorAll('.quadrant-header h2');
    
    quadrantTitles.forEach(title => {
        title.addEventListener('dblclick', function(e) {
            e.preventDefault();
            const quadrant = this.closest('.quadrant');
            const quadrantType = quadrant.dataset.quadrant;
            openFullscreenModal(quadrantType);
        });
    });
}

/**
 * 象限类型名称映射
 */
const quadrantNames = {
    'urgent-important': '紧急且重要',
    'important-not-urgent': '重要不紧急',
    'not-important-urgent': '不重要紧急',
    'not-important-not-urgent': '不紧急不重要'
};

/**
 * 打开全页显示模态窗口
 */
function openFullscreenModal(quadrantType) {
    const modal = document.getElementById('fullscreenModal');
    const modalTitle = document.getElementById('fullscreenModalTitle');
    const fullscreenTasks = document.getElementById('fullscreenTasks');
    const modalContainer = modal.querySelector('.fullscreen-modal');

    modal.classList.remove('closing');

    // 设置标题
    modalTitle.textContent = quadrantNames[quadrantType];
    
    // 存储当前象限类型以供拖拽使用
    modal.dataset.quadrant = quadrantType;
    if (modalContainer) {
        modalContainer.dataset.quadrant = quadrantType;
    }
    fullscreenTasks.dataset.quadrantType = quadrantType;
    
    // 渲染任务
    refreshFullscreenTasks();
    
    // 显示模态窗口
    modal.classList.add('show');
    
    // 防止背景滚动
    document.body.style.overflow = 'hidden';
    
    // 根据筛选状态自动启用拖拽排序
}

/**
 * 关闭全页显示模态窗口
 */
function closeFullscreenModal() {
    const modal = document.getElementById('fullscreenModal');
    if (!modal || modal.classList.contains('closing')) {
        return;
    }

    modal.classList.add('closing');
    modal.classList.remove('show');

    // 恢复背景滚动
    document.body.style.overflow = '';

    const CLEANUP_DELAY = 320;

    setTimeout(() => {
        if (!modal.classList.contains('closing')) {
            return;
        }
        cleanupFullscreenDragSorting();
        modal.classList.remove('closing');
        syncFullscreenToMain();
    }, CLEANUP_DELAY);
}

// 保留变量用于兼容现有调试逻辑
let fullscreenSortableInstance = null;

/**
 * 清理全屏模式拖拽实例（增强版）
 */
function cleanupFullscreenDragSorting() {
    try {
        if (fullscreenSortableInstance) {
            fullscreenSortableInstance.destroy();
            fullscreenSortableInstance = null;
            console.log('全屏拖拽实例已销毁');
        }
    } catch (error) {
        console.warn('销毁全屏拖拽实例时出现问题:', error);
    }

    const fullscreenTasks = document.getElementById('fullscreenTasks');
    if (fullscreenTasks) {
        fullscreenTasks.classList.remove('drag-active', 'drag-disabled', 'fullscreen-task-layout', 'empty-state');
        fullscreenTasks.innerHTML = '';
        delete fullscreenTasks.dataset.quadrantType;
    }

    const overlay = document.getElementById('fullscreenModal');
    if (overlay) {
        delete overlay.dataset.quadrant;
        overlay.classList.remove('show');
        const innerModal = overlay.querySelector('.fullscreen-modal');
        if (innerModal) {
            delete innerModal.dataset.quadrant;
        }
    }

    document.body.classList.remove('fullscreen-dragging-active');
    DragStateManager.clearAllDragStates();
    resumeQuadrantFocus();
}

/**
 * 初始化全屏模式拖拽功能
 * @param {string} quadrantType
 * @param {boolean} dragEnabled
 */
function initFullscreenDragSorting(quadrantType, dragEnabled) {
    const fullscreenTasks = document.getElementById('fullscreenTasks');

    if (!fullscreenTasks) {
        return;
    }

    if (fullscreenSortableInstance) {
        fullscreenSortableInstance.destroy();
        fullscreenSortableInstance = null;
    }

    if (!dragEnabled) {
        fullscreenTasks.classList.add('drag-disabled');
        return;
    }

    const draggableItems = fullscreenTasks.querySelectorAll('.fullscreen-task-card');
    if (draggableItems.length === 0) {
        return;
    }

    fullscreenSortableInstance = new Sortable(fullscreenTasks, {
        draggable: '.fullscreen-task-card',
        filter: '.fullscreen-filter-info',
        group: 'fullscreen-quadrant',
        animation: 220,
        ghostClass: 'fullscreen-sortable-ghost',
        chosenClass: 'fullscreen-sortable-chosen',
        dragClass: 'fullscreen-sortable-drag',
        fallbackOnBody: true,
        swapThreshold: 0.65,
        onStart: function(evt) {
            console.log('全屏拖拽开始:', evt.item.dataset.taskId);
            DragStateManager.clearAllDragStates();
            suspendQuadrantFocus();
            fullscreenTasks.classList.add('drag-active');
            evt.item.classList.add('dragging');
            document.body.classList.add('fullscreen-dragging-active');
        },
        onEnd: function(evt) {
            console.log('全屏拖拽结束:', evt.item.dataset.taskId, '新位置:', evt.newIndex);

            try {
                updateFullscreenTaskOrder(evt, quadrantType);
            } catch (error) {
                console.error('全屏拖拽更新顺序失败:', error);
                refreshFullscreenTasks();
            }

            setTimeout(() => {
                DragStateManager.clearAllDragStates();
                document.body.classList.remove('fullscreen-dragging-active');

                const validation = DragStateManager.validateDragStateClean();
                if (!validation.isClean) {
                    DragStateManager.clearAllDragStates(true);
                }

                resumeQuadrantFocus();
            }, 150);
        }
    });

    fullscreenTasks.classList.remove('drag-disabled');
    console.log('全屏拖拽初始化完成:', quadrantType);
}

/**
 * 在全页显示中渲染任务
 */
function renderFullscreenTask(task, options = {}) {
    const { dragEnabled = true } = options;
    const fullscreenTasks = document.getElementById('fullscreenTasks');
    
    const taskElement = document.createElement('div');
    taskElement.className = 'task fullscreen-task fullscreen-task-card';
    taskElement.draggable = dragEnabled;
    taskElement.dataset.taskId = task.id;
    taskElement.classList.toggle('drag-disabled', !dragEnabled);
    
    if (task.completed) {
        taskElement.classList.add('completed');
    }

    const statusText = task.completed ? '已完成' : '进行中';
    const statusClass = task.completed ? 'task-status completed' : 'task-status pending';

    taskElement.innerHTML = `
        <div class="task-header">
            <div class="task-title">${task.title}</div>
            <span class="${statusClass}">${statusText}</span>
        </div>
        ${task.description ? `<div class="task-body">${task.description}</div>` : ''}
        <div class="task-footer">
            <div class="task-meta">
                <span class="task-meta-label">创建时间</span>
                <span class="task-meta-value">${task.createdAt}</span>
            </div>
            <div class="task-actions">
                <button class="complete-btn" onclick="event.stopPropagation(); toggleCompleteAndSync(${task.id})" title="${task.completed ? '标记为未完成' : '标记为完成'}">
                    ${task.completed ? '↩' : '✓'}
                </button>
                <button class="delete-btn" onclick="event.stopPropagation(); deleteTaskAndSync(${task.id})" title="删除任务">
                    ×
                </button>
            </div>
        </div>
    `;
    
    // 添加双击编辑事件
    taskElement.addEventListener('dblclick', function(e) {
        e.preventDefault();
        e.stopPropagation();
        if (e.target.tagName !== 'BUTTON') {
            openEditTaskModal(task.id);
        }
    });
    
    fullscreenTasks.appendChild(taskElement);
}

/**
 * 设置键盘事件
 */
function setupKeyboardEvents() {
    // ESC键关闭弹窗
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeAddTaskModal();
            closeFullscreenModal();
            closeExportModal();
        }
    });

    // 点击遮罩层关闭弹窗
    document.getElementById('addTaskModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeAddTaskModal();
        }
    });

    // 点击遮罩层关闭全页显示弹窗
    document.getElementById('fullscreenModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeFullscreenModal();
        }
    });

    // 点击遮罩层关闭导出弹窗
    document.getElementById('exportTaskModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeExportModal();
        }
    });

    // 弹窗内回车提交
    document.getElementById('modalTaskTitle').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            addTaskFromModal();
        }
    });
    
    // 导出弹窗内的回车键事件
    document.getElementById('exportFileName').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            exportTasks();
        }
    });
}

/**
 * 清空表单
 */
function clearForm() {
    document.getElementById('taskTitle').value = '';
    document.getElementById('taskDescription').value = '';
    document.getElementById('taskQuadrant').value = 'urgent-important';
}

/**
 * 渲染任务到页面
 */
function renderTask(task) {
    const taskElement = document.createElement('div');
    taskElement.className = 'task';
    const dragEnabled = quadrantFilterState[task.quadrant] === 'all';
    taskElement.draggable = dragEnabled;
    taskElement.dataset.taskId = task.id;
    
    if (task.completed) {
        taskElement.classList.add('completed');
    }

    taskElement.classList.toggle('drag-disabled', !dragEnabled);

    const statusText = task.completed ? '已完成' : '进行中';
    const statusClass = task.completed ? 'task-status completed' : 'task-status pending';

    taskElement.innerHTML = `
        <div class="task-header">
            <div class="task-title">${task.title}</div>
            <span class="${statusClass}">${statusText}</span>
        </div>
        ${task.description ? `<div class="task-body">${task.description}</div>` : ''}
        <div class="task-footer">
            <div class="task-meta">
                <span class="task-meta-label">创建时间</span>
                <span class="task-meta-value">${task.createdAt}</span>
            </div>
            <div class="task-actions">
                <button class="complete-btn" onclick="event.stopPropagation(); toggleComplete(${task.id})" title="${task.completed ? '标记为未完成' : '标记为完成'}">
                    ${task.completed ? '↩' : '✓'}
                </button>
                <button class="delete-btn" onclick="event.stopPropagation(); deleteTask(${task.id})" title="删除任务">
                    ×
                </button>
            </div>
        </div>
    `;

    // 添加拖拽事件
    taskElement.addEventListener('dragstart', handleDragStart);
    taskElement.addEventListener('dragend', handleDragEnd);
    
    // 添加双击编辑事件
    taskElement.addEventListener('dblclick', function(e) {
        e.preventDefault();
        e.stopPropagation();
        if (e.target.tagName !== 'BUTTON') {
            openEditTaskModal(task.id);
        }
    });

    // 添加到对应的象限
    const zone = document.getElementById(`${task.quadrant}-zone`);
    zone.appendChild(taskElement);
}

function getQuadrantTasks(quadrantType, options = {}) {
    const { respectFilter = true } = options;
    const filter = respectFilter ? quadrantFilterState[quadrantType] || 'all' : 'all';
    return tasks
        .filter(task => task.quadrant === quadrantType)
        .filter(task => {
            if (filter === 'completed') {
                return task.completed;
            }
            if (filter === 'pending') {
                return !task.completed;
            }
            return true;
        })
        .sort((a, b) => (a.order || 0) - (b.order || 0));
}

function setQuadrantDraggingEnabled(quadrantType, enabled) {
    const zoneId = `${quadrantType}-zone`;
    const zone = document.getElementById(zoneId);
    if (zone) {
        zone.querySelectorAll('.task').forEach(taskElement => {
            taskElement.setAttribute('draggable', enabled);
            taskElement.classList.toggle('drag-disabled', !enabled);
        });
        zone.classList.toggle('drag-disabled', !enabled);
    }

    const sortableInstance = dropZoneSortables[zoneId];
    if (sortableInstance) {
        sortableInstance.option('disabled', !enabled);
    }
}

function refreshQuadrant(quadrantType) {
    const zone = document.getElementById(`${quadrantType}-zone`);
    if (!zone) {
        return;
    }

    zone.innerHTML = '';

    const quadrantTasks = getQuadrantTasks(quadrantType);
    quadrantTasks.forEach(task => renderTask(task));

    const dragEnabled = quadrantFilterState[quadrantType] === 'all';
    setQuadrantDraggingEnabled(quadrantType, dragEnabled);
}

function updateQuadrantFilterButtons(quadrantType) {
    const buttons = document.querySelectorAll(`.quadrant-filter-btn[data-quadrant="${quadrantType}"]`);
    const activeFilter = quadrantFilterState[quadrantType];
    buttons.forEach(button => {
        const isActive = button.dataset.filter === activeFilter;
        button.classList.toggle('active', isActive);
        button.setAttribute('aria-pressed', isActive ? 'true' : 'false');
    });
}

function isFullscreenModalOpenForQuadrant(quadrantType) {
    const fullscreenModal = document.getElementById('fullscreenModal');
    if (!fullscreenModal || !fullscreenModal.classList.contains('show')) {
        return false;
    }

    const fullscreenTasks = document.getElementById('fullscreenTasks');
    return fullscreenTasks && fullscreenTasks.dataset.quadrantType === quadrantType;
}

function initQuadrantFilters() {
    const filterButtons = document.querySelectorAll('.quadrant-filter-btn');
    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            const quadrant = button.dataset.quadrant;
            const filter = button.dataset.filter;
            if (!quadrant || !filter) {
                return;
            }

            const currentFilter = quadrantFilterState[quadrant];
            quadrantFilterState[quadrant] = currentFilter === filter ? 'all' : filter;
            updateQuadrantFilterButtons(quadrant);
            refreshQuadrant(quadrant);

            if (isFullscreenModalOpenForQuadrant(quadrant)) {
                refreshFullscreenTasks();
            }
        });
    });

    QUADRANT_TYPES.forEach(quadrant => updateQuadrantFilterButtons(quadrant));
}

/**
 * 刷新所有任务显示
 */
function refreshAllTasks() {
    try {
        QUADRANT_TYPES.forEach(quadrant => refreshQuadrant(quadrant));
        
        // 如果全页显示模态窗口打开，也需要刷新
        const fullscreenModal = document.getElementById('fullscreenModal');
        if (fullscreenModal && fullscreenModal.classList.contains('show')) {
            refreshFullscreenTasks();
        }
        
        console.log('所有任务列表已刷新');
        
    } catch (error) {
        console.error('刷新任务列表失败:', error);
        
        // 错误恢复：重新加载数据
        loadTasksFromLocalStorage();
        
        // 递归重试一次（防止无限递归）
        if (!refreshAllTasks._retrying) {
            refreshAllTasks._retrying = true;
            setTimeout(() => {
                refreshAllTasks();
                refreshAllTasks._retrying = false;
            }, 100);
        }
    }
}

/**
 * 增强版拖拽开始处理
 */
function handleDragStart(e) {
    try {
        // 先清理之前可能残留的状态
        DragStateManager.clearAllDragStates();
        
        // 拖拽期间暂停象限聚焦
        suspendQuadrantFocus();

        // 添加拖拽状态
        e.target.classList.add('dragging');
        e.dataTransfer.setData('text/plain', e.target.dataset.taskId);
        
        console.log('拖拽开始:', e.target.dataset.taskId);
        
    } catch (error) {
        console.error('拖拽开始处理失败:', error);
        DragStateManager.clearAllDragStates();
    }
}

/**
 * 增强版拖拽结束处理
 */
function handleDragEnd(e) {
    try {
        // 立即移除拖拽状态
        e.target.classList.remove('dragging');
        
        resumeQuadrantFocus();

        console.log('拖拽结束:', e.target.dataset.taskId);
        
        // 延迟执行完整的状态清理，确保SortableJS完成所有操作
        setTimeout(() => {
            DragStateManager.clearAllDragStates();
            
            // 验证清理结果
            const validation = DragStateManager.validateDragStateClean();
            if (!validation.isClean) {
                console.warn('第一次清理不完整，执行强制清理');
                DragStateManager.clearAllDragStates(true);
            }
            
            // 强制重绘
            document.body.offsetHeight;
            
        }, 100);
        
    } catch (error) {
        console.error('拖拽结束处理失败:', error);
        // 错误时强制清理所有状态
        DragStateManager.clearAllDragStates(true);
    }
}

/**
 * 初始化拖拽区域（增强版）
 */
function initDropZones() {
    const dropZones = document.querySelectorAll('.drop-zone');
    
    dropZones.forEach(zone => {
        zone.addEventListener('dragover', handleDragOver);
        zone.addEventListener('drop', handleDrop);
        zone.addEventListener('dragenter', handleDragEnter);
        zone.addEventListener('dragleave', handleDragLeave);
        
        // 初始化 SortableJS 用于拖拽排序（增强版）
        const sortableInstance = new Sortable(zone, {
            group: 'quadrants',
            animation: 200,
            ghostClass: 'sortable-ghost',
            chosenClass: 'sortable-chosen',
            dragClass: 'sortable-drag',
            forceFallback: false,
            fallbackOnBody: true,
            swapThreshold: 0.65,
            
            onStart: function(evt) {
                console.log('常规模式拖拽开始:', evt.item.dataset.taskId);
                
                // 确保清理之前的状态
                DragStateManager.clearAllDragStates();

                // 拖拽期间暂停象限聚焦
                suspendQuadrantFocus();
                
                // 添加拖拽状态
                evt.item.classList.add('dragging');
                
                // 全局拖拽状态标记
                document.body.classList.add('dragging-active');
            },
            
            onEnd: function(evt) {
                console.log('常规模式拖拽结束:', evt.item.dataset.taskId);
                
                try {
                    const taskId = parseInt(evt.item.dataset.taskId);
                    const newQuadrant = evt.to.closest('.quadrant').dataset.quadrant;
                    const oldQuadrant = evt.from.closest('.quadrant').dataset.quadrant;
                    const newIndex = evt.newIndex;
                    
                    // 更新任务位置
                    updateTaskPosition(taskId, newQuadrant, newIndex, oldQuadrant);
                    
                } catch (error) {
                    console.error('常规模式拖拽结束处理失败:', error);
                }
                
                // 延迟清理状态，确保SortableJS完成所有操作
                setTimeout(() => {
                    DragStateManager.clearAllDragStates();
                    document.body.classList.remove('dragging-active');
                    
                    // 验证清理结果
                    const validation = DragStateManager.validateDragStateClean();
                    if (!validation.isClean) {
                        console.warn('常规模式拖拽状态清理不完整，执行强制清理');
                        DragStateManager.clearAllDragStates(true);
                    }
                    
                    // 强制重绘
                    document.body.offsetHeight;
                    
                }, 150);

                resumeQuadrantFocus();
            },
            
            onMove: function(evt) {
                // 拖拽移动时的验证，返回false可以阻止移动
                return true;
            },
            
            onSort: function(evt) {
                // 排序完成后的清理
                console.log('常规模式排序完成');
            }
        });

        dropZoneSortables[zone.id] = sortableInstance;

        const quadrantType = zone.closest('.quadrant')?.dataset.quadrant;
        if (quadrantType) {
            const dragEnabled = quadrantFilterState[quadrantType] === 'all';
            sortableInstance.option('disabled', !dragEnabled);
        }
    });

    console.log('常规模式拖拽区域初始化完成');
}

/**
 * 拖拽悬停处理
 */
function handleDragOver(e) {
    e.preventDefault();
}

/**
 * 拖拽进入处理
 */
function handleDragEnter(e) {
    e.preventDefault();
    e.target.classList.add('drag-over');
}

/**
 * 增强版拖拽离开处理
 */
function handleDragLeave(e) {
    if (!e.target.contains(e.relatedTarget)) {
        e.target.classList.remove('drag-over');
        
        // 延迟清理，防止快速移动时的状态混乱
        setTimeout(() => {
            if (!e.target.matches(':hover')) {
                e.target.classList.remove('drag-over');
            }
        }, 50);
    }
}

/**
 * 打开编辑任务弹窗
 */
function openEditTaskModal(taskId) {
    const task = tasks.find(t => t.id === taskId);
    if (!task) {
        showToast('未找到任务，无法编辑', 2000);
        return;
    }

    openAddTaskModal(task.quadrant, { mode: 'edit', task });
}

/**
 * 更新任务位置和象限
 */
function updateTaskPosition(taskId, newQuadrant, newIndex, oldQuadrant) {
    const task = tasks.find(t => t.id === taskId);
    if (!task) return;
    
    // 更新任务的象限
    task.quadrant = newQuadrant;
    
    // 重新计算所有任务的顺序
    reorderTasks(newQuadrant, taskId, newIndex);
    
    // 如果任务从一个象限移动到另一个象限，需要重新计算原象限的顺序
    if (oldQuadrant !== newQuadrant) {
        reorderTasks(oldQuadrant);
    }
    
    // 保存到本地存储
    saveTasksToLocalStorage();
}

/**
 * 重新排序指定象限的任务
 */
function reorderTasks(quadrant, movedTaskId = null, newIndex = null) {
    const quadrantTasks = tasks
        .filter(task => task.quadrant === quadrant)
        .sort((a, b) => (a.order || 0) - (b.order || 0));
    
    if (movedTaskId !== null && newIndex !== null) {
        // 找到被移动的任务
        const movedTaskIndex = quadrantTasks.findIndex(task => task.id === movedTaskId);
        if (movedTaskIndex !== -1) {
            // 移除被移动的任务
            const [movedTask] = quadrantTasks.splice(movedTaskIndex, 1);
            // 在新位置插入
            quadrantTasks.splice(newIndex, 0, movedTask);
        }
    }
    
    // 重新分配顺序
    quadrantTasks.forEach((task, index) => {
        task.order = index;
    });
}

// ================== 导出功能相关函数 ==================

/**
 * 导出服务类 - 负责将任务数据转换为Markdown格式
 */
class ExportService {
    constructor() {
        this.quadrantNames = {
            'urgent-important': '🔴 紧急且重要',
            'important-not-urgent': '🟢 重要不紧急', 
            'not-important-urgent': '🟡 不重要紧急',
            'not-important-not-urgent': '⚪ 不紧急不重要'
        };
        
        this.quadrantEmojis = {
            'urgent-important': '🔴',
            'important-not-urgent': '🟢',
            'not-important-urgent': '🟡', 
            'not-important-not-urgent': '⚪'
        };
    }
    
    /**
     * 收集任务数据根据导出配置
     * @param {Object} config 导出配置
     * @returns {Object} 处理后的导出数据
     */
    collectTasksData(config) {
        const exportData = {
            title: config.fileName || '四象限任务导出',
            generatedAt: new Date().toLocaleString('zh-CN'),
            quadrants: {},
            statistics: {
                total: 0,
                completed: 0,
                pending: 0,
                quadrantCounts: {}
            }
        };
        
        // 初始化象限数据
        Object.keys(this.quadrantNames).forEach(quadrant => {
            exportData.quadrants[quadrant] = [];
            exportData.statistics.quadrantCounts[quadrant] = { total: 0, completed: 0 };
        });
        
        // 过滤和分组任务
        tasks.forEach(task => {
            // 检查是否包含该象限
            if (!config.includeQuadrants.includes(task.quadrant)) {
                return;
            }
            
            // 检查是否包含已完成任务
            if (!config.includeCompleted && task.completed) {
                return;
            }
            
            exportData.quadrants[task.quadrant].push(task);
            exportData.statistics.total++;
            exportData.statistics.quadrantCounts[task.quadrant].total++;
            
            if (task.completed) {
                exportData.statistics.completed++;
                exportData.statistics.quadrantCounts[task.quadrant].completed++;
            } else {
                exportData.statistics.pending++;
            }
        });
        
        // 按顺序排序每个象限的任务
        Object.keys(exportData.quadrants).forEach(quadrant => {
            exportData.quadrants[quadrant].sort((a, b) => (a.order || 0) - (b.order || 0));
        });
        
        return exportData;
    }
    
    /**
     * 格式化任务为Markdown
     * @param {Object} task 任务对象
     * @param {Object} config 导出配置
     * @returns {string} Markdown格式的任务内容
     */
    formatTask(task, config) {
        let markdown = '';
        
        // 任务标题和状态
        const statusIcon = task.completed ? '✅' : '⏳';
        markdown += `### ${statusIcon} ${task.title}\n`;
        
        // 任务描述
        if (config.includeDescription && task.description) {
            markdown += `- **描述**: ${task.description}\n`;
        }
        
        // 元数据信息
        if (config.includeMetadata) {
            markdown += `- **状态**: ${task.completed ? '已完成' : '进行中'}\n`;
            markdown += `- **创建时间**: ${task.createdAt}\n`;
        }
        
        markdown += '\n';
        return markdown;
    }
    
    /**
     * 生成统计信息的Markdown
     * @param {Object} data 导出数据
     * @returns {string} 统计信息的Markdown内容
     */
    generateStatistics(data) {
        let markdown = '---\n\n## 📊 统计信息\n\n';
        
        const completionRate = data.statistics.total > 0 
            ? (data.statistics.completed / data.statistics.total * 100).toFixed(1)
            : 0;
        
        markdown += `- **总任务数**: ${data.statistics.total}\n`;
        markdown += `- **完成率**: ${completionRate}%\n`;
        markdown += `- **已完成**: ${data.statistics.completed}\n`;
        markdown += `- **进行中**: ${data.statistics.pending}\n\n`;
        
        markdown += '- **各象限分布**:\n';
        Object.keys(this.quadrantNames).forEach(quadrant => {
            const stats = data.statistics.quadrantCounts[quadrant];
            if (stats.total > 0) {
                const quadrantRate = (stats.total / data.statistics.total * 100).toFixed(1);
                markdown += `  - ${this.quadrantNames[quadrant]}: ${stats.total}个 (${quadrantRate}%)\n`;
            }
        });
        
        return markdown;
    }
    
    /**
     * 导出任务为Markdown格式
     * @param {Object} config 导出配置
     * @returns {string} 完整的Markdown内容
     */
    exportToMarkdown(config, precomputedData = null) {
        const data = precomputedData || this.collectTasksData(config);
        let markdown = '';
        
        // 文档标题和元信息
        markdown += `# ${data.title}\n\n`;
        markdown += `**导出时间**: ${data.generatedAt}\n`;
        markdown += `**任务总数**: ${data.statistics.total}\n`;
        markdown += `**已完成**: ${data.statistics.completed}\n`;
        markdown += `**未完成**: ${data.statistics.pending}\n\n`;
        
        // 按象限输出任务
        Object.keys(this.quadrantNames).forEach(quadrant => {
            const quadrantTasks = data.quadrants[quadrant];
            if (quadrantTasks.length === 0) return;
            
            markdown += `## ${this.quadrantNames[quadrant]} (${quadrantTasks.length}个任务)\n\n`;
            
            quadrantTasks.forEach(task => {
                markdown += this.formatTask(task, config);
            });
        });
        
        // 添加统计信息
        if (config.includeStatistics) {
            markdown += this.generateStatistics(data);
        }
        
        return markdown;
    }
}

/**
 * 文件工具类 - 负责文件下载操作
 */
class FileUtils {
    /**
     * 创建Blob对象
     * @param {string} content 文件内容
     * @param {string} type MIME类型
     * @returns {Blob} Blob对象
     */
    static createBlob(content, type = 'text/markdown;charset=utf-8') {
        return new Blob([content], { type });
    }
    
    /**
     * 生成下载链接并触发下载
     * @param {Blob} blob Blob对象
     * @param {string} filename 文件名
     */
    static downloadFile(blob, filename) {
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }
}

// 创建导出服务实例
const exportService = new ExportService();

// ================== 导出界面交互函数 ==================

/**
 * 打开导出配置弹窗
 */
function openExportModal() {
    const modal = document.getElementById('exportTaskModal');
    modal.classList.add('show');
    
    // 重置表单为默认值
    resetExportForm();
    
    // 初始化预览
    setTimeout(() => {
        previewExport();
        document.getElementById('exportFileName').focus();
    }, 100);
    
    // 添加配置变更监听器
    setupExportConfigListeners();
}

/**
 * 关闭导出配置弹窗
 */
function closeExportModal() {
    const modal = document.getElementById('exportTaskModal');
    modal.classList.remove('show');
    
    // 移除事件监听器
    removeExportConfigListeners();
}

/**
 * 重置导出表单为默认值
 */
function generateExportFileName() {
    const now = new Date();
    const pad = value => value.toString().padStart(2, '0');
    return `任务_${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}-${pad(now.getMinutes())}`;
}

function resetExportForm() {
    // 设置默认文件名
    document.getElementById('exportFileName').value = generateExportFileName();
    
    // 默认选中所有象限
    document.getElementById('exportUrgentImportant').checked = true;
    document.getElementById('exportImportantNotUrgent').checked = true;
    document.getElementById('exportNotImportantUrgent').checked = true;
    document.getElementById('exportNotImportantNotUrgent').checked = true;
    
    // 默认选中所有选项
    document.getElementById('includeCompleted').checked = true;
    document.getElementById('includeDescription').checked = true;
    document.getElementById('includeMetadata').checked = true;
    document.getElementById('includeStatistics').checked = true;
}

/**
 * 获取当前导出配置
 * @returns {Object} 导出配置对象
 */
function getExportConfig() {
    const config = {
        fileName: document.getElementById('exportFileName').value.trim(),
        includeQuadrants: [],
        includeCompleted: document.getElementById('includeCompleted').checked,
        includeDescription: document.getElementById('includeDescription').checked,
        includeMetadata: document.getElementById('includeMetadata').checked,
        includeStatistics: document.getElementById('includeStatistics').checked
    };

    if (!config.fileName) {
        config.fileName = generateExportFileName();
    }
    
    // 收集选中的象限
    if (document.getElementById('exportUrgentImportant').checked) {
        config.includeQuadrants.push('urgent-important');
    }
    if (document.getElementById('exportImportantNotUrgent').checked) {
        config.includeQuadrants.push('important-not-urgent');
    }
    if (document.getElementById('exportNotImportantUrgent').checked) {
        config.includeQuadrants.push('not-important-urgent');
    }
    if (document.getElementById('exportNotImportantNotUrgent').checked) {
        config.includeQuadrants.push('not-important-not-urgent');
    }
    
    return config;
}

/**
 * 预览导出内容
 */
function previewExport() {
    try {
        const config = getExportConfig();
        const previewElement = document.getElementById('exportPreview');
        if (!previewElement) {
            console.warn('未找到预览区域 exportPreview');
            return;
        }

        previewElement.textContent = '正在生成预览...';

        const effectiveConfig = {
            ...config,
            fileName: config.fileName || generateExportFileName()
        };

        // 验证配置
        if (effectiveConfig.includeQuadrants.length === 0) {
            previewElement.textContent = '请至少选择一个象限';
            return;
        }

        const exportData = exportService.collectTasksData(effectiveConfig);
        if (exportData.statistics.total === 0) {
            previewElement.textContent = '当前配置下没有可导出的任务';
            return;
        }

        // 生成预览内容
        const markdown = exportService.exportToMarkdown(effectiveConfig, exportData);
        previewElement.textContent = markdown;
        previewElement.scrollTop = 0;

    } catch (error) {
        console.error('预览生成失败:', error);
        const previewElement = document.getElementById('exportPreview');
        if (previewElement) {
            previewElement.textContent = '预览生成失败，请检查配置';
        }
    }
}

/**
 * 执行导出操作
 */
function exportTasks() {
    try {
        const config = getExportConfig();
        
        // 验证配置
        if (!config.fileName) {
            alert('请输入文件名');
            document.getElementById('exportFileName').focus();
            return;
        }
        
        if (config.includeQuadrants.length === 0) {
            alert('请至少选择一个象限');
            return;
        }
        
        // 生成Markdown内容
        const markdown = exportService.exportToMarkdown(config);
        
        // 创建文件并下载
        const blob = FileUtils.createBlob(markdown);
        const fileName = `${config.fileName}.md`;
        FileUtils.downloadFile(blob, fileName);
        
        // 显示成功提示
        showExportSuccess(fileName);
        
        // 关闭弹窗
        closeExportModal();
        
    } catch (error) {
        console.error('导出失败:', error);
        alert('导出失败，请重试');
    }
}

/**
 * 显示导出成功提示
 * @param {string} fileName 导出的文件名
 */
function showExportSuccess(fileName) {
    // 创建临时提示元素
    const notification = document.createElement('div');
    notification.className = 'export-success-notification';
    notification.innerHTML = `
        <div class="notification-content">
            <span class="notification-icon">✅</span>
            <span class="notification-text">导出成功：${fileName}</span>
        </div>
    `;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #28a745;
        color: white;
        padding: 15px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        animation: slideInRight 0.3s ease;
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
            if (notification.parentNode) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

/**
 * 设置导出配置变更监听器
 */
function setupExportConfigListeners() {
    const configElements = [
        'exportFileName',
        'exportUrgentImportant',
        'exportImportantNotUrgent', 
        'exportNotImportantUrgent',
        'exportNotImportantNotUrgent',
        'includeCompleted',
        'includeDescription',
        'includeMetadata',
        'includeStatistics'
    ];
    
    configElements.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('change', previewExport);
            element.addEventListener('input', previewExport);
        }
    });
}

/**
 * 移除导出配置变更监听器
 */
function removeExportConfigListeners() {
    const configElements = [
        'exportFileName',
        'exportUrgentImportant',
        'exportImportantNotUrgent',
        'exportNotImportantUrgent', 
        'exportNotImportantNotUrgent',
        'includeCompleted',
        'includeDescription',
        'includeMetadata',
        'includeStatistics'
    ];
    
    configElements.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.removeEventListener('change', previewExport);
            element.removeEventListener('input', previewExport);
        }
    });
}

// ================== 调试和测试功能 ==================

/**
 * 测试拖拽状态管理器功能
 * 可在浏览器控制台中调用 testDragStateManager() 来测试
 */
function testDragStateManager() {
    console.log('开始测试拖拽状态管理器...');
    
    try {
        // 测试基础功能
        console.log('1. 测试拖拽状态检测');
        const hasStates = DragStateManager.hasRemainingDragStates();
        console.log('当前是否有残留拖拽状态:', hasStates);
        
        console.log('2. 测试状态验证');
        const validation = DragStateManager.validateDragStateClean();
        console.log('状态验证结果:', validation);
        
        console.log('3. 测试状态清理');
        DragStateManager.clearAllDragStates();
        console.log('状态清理完成');
        
        console.log('4. 测试自动修复');
        const fixed = DragStateManager.autoFixDragStates();
        console.log('自动修复结果:', fixed);
        
        console.log('✅ 拖拽状态管理器测试通过!');
        return true;
        
    } catch (error) {
        console.error('❌ 拖拽状态管理器测试失败:', error);
        return false;
    }
}

/**
 * 模拟拖拽问题，用于测试修复功能
 */
function simulateDragIssue() {
    console.log('模拟拖拽问题...');
    
    // 人为添加一些拖拽状态类
    const tasks = document.querySelectorAll('.task');
    const fullscreenTasks = document.querySelectorAll('.fullscreen-task');
    
    if (tasks.length > 0) {
        tasks[0].classList.add('sortable-chosen');
        tasks[0].classList.add('dragging');
        console.log('已向常规任务添加拖拽状态类');
    }
    
    if (fullscreenTasks.length > 0) {
        fullscreenTasks[0].classList.add('fullscreen-sortable-ghost');
        console.log('已向全屏任务添加拖拽状态类');
    }
    
    // 添加拖拽区域状态
    const dropZones = document.querySelectorAll('.drop-zone');
    if (dropZones.length > 0) {
        dropZones[0].classList.add('drag-over');
        console.log('已向拖拽区域添加状态类');
    }
    
    console.log('拖拽问题模拟完成，可以调用 DragStateManager.autoFixDragStates() 或 manualResetDragState() 来测试修复');
}

/**
 * 全面诊断拖拽系统状态
 */
function diagnoseDragSystem() {
    console.log('🔍 开始诊断拖拽系统状态...');
    
    const report = {
        timestamp: new Date().toLocaleString(),
        dragStates: {},
        sortableInstances: {},
        globalStates: {},
        issues: []
    };
    
    // 检查拖拽状态类
    DragStateManager.DRAG_CLASSES.forEach(className => {
        const elements = document.querySelectorAll(`.${className}`);
        report.dragStates[className] = {
            count: elements.length,
            elements: Array.from(elements).map(el => ({
                tagName: el.tagName,
                className: el.className,
                id: el.id,
                dataset: el.dataset
            }))
        };
        
        if (elements.length > 0) {
            report.issues.push(`发现残留状态类: ${className} (${elements.length}个元素)`);
        }
    });
    
    // 检查SortableJS实例
    report.sortableInstances.fullscreenInstance = {
        exists: fullscreenSortableInstance !== null,
        type: fullscreenSortableInstance ? typeof fullscreenSortableInstance : 'null'
    };
    
    // 检查全局状态
    report.globalStates.bodyClasses = Array.from(document.body.classList);
    report.globalStates.draggingActive = document.body.classList.contains('dragging-active');
    report.globalStates.fullscreenDraggingActive = document.body.classList.contains('fullscreen-dragging-active');
    
    // 检查模态窗口状态
    const fullscreenModal = document.getElementById('fullscreenModal');
    report.globalStates.fullscreenModalOpen = fullscreenModal ? fullscreenModal.classList.contains('show') : false;
    
    // 检查任务数量
    report.globalStates.taskCounts = {
        totalTasks: tasks.length,
        regularTaskElements: document.querySelectorAll('.task').length,
        fullscreenTaskElements: document.querySelectorAll('.fullscreen-task').length
    };
    
    // 输出诊断报告
    console.log('📊 拖拽系统诊断报告:');
    console.table(report.dragStates);
    console.log('SortableJS实例状态:', report.sortableInstances);
    console.log('全局状态:', report.globalStates);
    
    if (report.issues.length > 0) {
        console.warn('🚨 发现问题:');
        report.issues.forEach(issue => console.warn(`- ${issue}`));
        console.log('💡 建议执行: manualResetDragState() 或 DragStateManager.autoFixDragStates()');
    } else {
        console.log('✅ 拖拽系统状态正常');
    }
    
    return report;
}

// 在开发环境中暴露调试函数到全局作用域
if (typeof window !== 'undefined') {
    window.testDragStateManager = testDragStateManager;
    window.simulateDragIssue = simulateDragIssue;
    window.diagnoseDragSystem = diagnoseDragSystem;
    window.manualResetDragState = manualResetDragState;
    window.DragStateManager = DragStateManager;
    window.previewExport = previewExport;
    window.exportTasks = exportTasks;
    window.openExportModal = openExportModal;
    window.closeExportModal = closeExportModal;
    
    console.log('🛠️ 调试工具已加载到全局作用域:');
    console.log('- testDragStateManager(): 测试拖拽状态管理器');
    console.log('- simulateDragIssue(): 模拟拖拽问题');
    console.log('- diagnoseDragSystem(): 诊断拖拽系统');
    console.log('- manualResetDragState(): 手动重置拖拽状态');
    console.log('- DragStateManager: 拖拽状态管理器类');
}

// ================== 全屏模式拖拽功能 ==================

/**
 * 更新全屏模式下的任务顺序
 * @param {Object} evt SortableJS事件对象
 * @param {string} quadrantType 象限类型
 */
function updateFullscreenTaskOrder(evt, quadrantType) {
    const taskId = parseInt(evt.item.dataset.taskId);
    const newIndex = evt.newIndex;
    const oldIndex = evt.oldIndex;
    
    console.log(`更新任务顺序: ID=${taskId}, 旧位置=${oldIndex}, 新位置=${newIndex}`);
    
    // 如果位置没有变化，直接返回
    if (oldIndex === newIndex) {
        return;
    }
    
    try {
        // 重新排序象限内的任务
        reorderQuadrantTasks(quadrantType, taskId, newIndex);
        
        // 保存到本地存储
        saveTasksToLocalStorage();
        
        // 验证任务顺序的正确性
        validateTaskOrder(quadrantType);
        
        console.log('全屏模式任务顺序更新成功');
        
    } catch (error) {
        console.error('更新任务顺序失败:', error);
        
        // 错误时恢复任务列表
        refreshFullscreenTasks();
    }
}

/**
 * 重新排序象限内的任务
 * @param {string} quadrant 象限类型
 * @param {number} movedTaskId 被移动的任务ID
 * @param {number} newIndex 新位置索引
 */
function reorderQuadrantTasks(quadrant, movedTaskId, newIndex) {
    // 获取象限内所有任务，按当前顺序排列
    const quadrantTasks = tasks
        .filter(task => task.quadrant === quadrant)
        .sort((a, b) => (a.order || 0) - (b.order || 0));
    
    // 找到被移动的任务
    const movedTaskIndex = quadrantTasks.findIndex(task => task.id === movedTaskId);
    if (movedTaskIndex === -1) {
        throw new Error(`未找到任务 ID: ${movedTaskId}`);
    }
    
    // 移除被移动的任务
    const [movedTask] = quadrantTasks.splice(movedTaskIndex, 1);
    
    // 在新位置插入
    quadrantTasks.splice(newIndex, 0, movedTask);
    
    // 重新分配顺序
    quadrantTasks.forEach((task, index) => {
        task.order = index;
    });
    
    console.log(`象限 ${quadrant} 任务重排序完成:`, quadrantTasks.map(t => `${t.title}(${t.order})`));
}

/**
 * 同步全屏模式数据到主界面
 */
function syncFullscreenToMain() {
    console.log('开始同步全屏模式数据到主界面');
    
    try {
        // 延迟刷新主界面，确保数据已经保存
        setTimeout(() => {
            refreshAllTasks();
            console.log('主界面任务列表已刷新');
        }, 50);
        
    } catch (error) {
        console.error('数据同步失败:', error);
    }
}

/**
 * 验证任务顺序的正确性
 * @param {string} quadrant 象限类型
 */
function validateTaskOrder(quadrant) {
    const quadrantTasks = tasks.filter(t => t.quadrant === quadrant);
    const orders = quadrantTasks.map(t => t.order || 0).sort((a, b) => a - b);
    
    // 检查顺序是否连续（从0开始）
    for (let i = 0; i < orders.length; i++) {
        if (orders[i] !== i) {
            console.warn(`任务顺序不连续，执行修复: ${quadrant}`, orders);
            repairTaskOrder(quadrant);
            break;
        }
    }
}

/**
 * 修复任务顺序
 * @param {string} quadrant 象限类型  
 */
function repairTaskOrder(quadrant) {
    const quadrantTasks = tasks
        .filter(task => task.quadrant === quadrant)
        .sort((a, b) => (a.order || 0) - (b.order || 0));
    
    // 重新分配连续顺序
    quadrantTasks.forEach((task, index) => {
        task.order = index;
    });
    
    // 保存修复结果
    saveTasksToLocalStorage();
    
    console.log(`象限 ${quadrant} 任务顺序已修复`);
}

// ================== 全屏模式同步操作函数 ==================

/**
 * 在全屏模式中切换任务完成状态并同步
 * @param {number} taskId 任务ID
 */
function toggleCompleteAndSync(taskId) {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
        task.completed = !task.completed;
        
        // 立即保存数据
        saveTasksToLocalStorage();
        
        // 刷新全屏显示
        refreshFullscreenTasks();
        
        console.log(`任务 ${taskId} 完成状态已更新: ${task.completed}`);
    }
}

/**
 * 在全屏模式中删除任务并同步
 * @param {number} taskId 任务ID
 */
function deleteTaskAndSync(taskId) {
    if (confirm('确定要删除这个任务吗？')) {
        const task = tasks.find(t => t.id === taskId);
        const quadrantType = task ? task.quadrant : null;
        
        // 删除任务
        tasks = tasks.filter(t => t.id !== taskId);
        
        // 重新排序该象限的其他任务
        if (quadrantType) {
            reorderTasksAfterDeletion(quadrantType);
        }
        
        // 保存数据
        saveTasksToLocalStorage();
        
        // 刷新全屏显示
        refreshFullscreenTasks();
        
        console.log(`任务 ${taskId} 已删除`);
    }
}

/**
 * 删除任务后重新排序
 * @param {string} quadrant 象限类型
 */
function reorderTasksAfterDeletion(quadrant) {
    const quadrantTasks = tasks
        .filter(task => task.quadrant === quadrant)
        .sort((a, b) => (a.order || 0) - (b.order || 0));
    
    // 重新分配连续顺序
    quadrantTasks.forEach((task, index) => {
        task.order = index;
    });
}

/**
 * 增强的刷新全屏任务函数
 */
function refreshFullscreenTasks() {
    const fullscreenTasks = document.getElementById('fullscreenTasks');
    if (!fullscreenTasks) {
        return;
    }

    const currentQuadrantType = fullscreenTasks.dataset?.quadrantType;

    if (currentQuadrantType) {
        const quadrantTasks = getQuadrantTasks(currentQuadrantType);
        const activeFilter = quadrantFilterState[currentQuadrantType];
        const isFiltered = activeFilter !== 'all';

        fullscreenTasks.innerHTML = '';
        fullscreenTasks.classList.remove('empty-state');
        fullscreenTasks.classList.add('fullscreen-task-layout');

        if (isFiltered) {
            const filterInfo = document.createElement('div');
            filterInfo.className = 'fullscreen-filter-info';
            filterInfo.textContent = activeFilter === 'completed' ? '当前筛选：仅显示已完成任务' : '当前筛选：仅显示进行中任务';
            fullscreenTasks.appendChild(filterInfo);
        }

        const dragEnabled = !isFiltered;

        if (quadrantTasks.length === 0) {
            if (fullscreenSortableInstance) {
                fullscreenSortableInstance.destroy();
                fullscreenSortableInstance = null;
            }
            const emptyMessage = isFiltered ? '当前筛选下暂无任务' : '该象限暂无任务';
            fullscreenTasks.innerHTML = `<div class="empty-fullscreen-message">${emptyMessage}</div>`;
            fullscreenTasks.classList.add('empty-state');
            fullscreenTasks.classList.remove('fullscreen-task-layout');
            fullscreenTasks.classList.remove('drag-disabled');
        } else {
            quadrantTasks.forEach(task => renderFullscreenTask(task, { dragEnabled }));
            initFullscreenDragSorting(currentQuadrantType, dragEnabled);
        }
    }
}

// ================== 数据完整性校验和错误处理 ==================

/**
 * 全面的数据完整性校验
 * @returns {Object} 校验结果
 */
function validateAllTasksData() {
    const validation = {
        isValid: true,
        errors: [],
        warnings: [],
        statistics: {
            totalTasks: tasks.length,
            quadrantCounts: {},
            orderIssues: 0,
            duplicateIds: 0
        }
    };
    
    try {
        // 检查任务ID唯一性
        const taskIds = tasks.map(t => t.id);
        const uniqueIds = new Set(taskIds);
        if (taskIds.length !== uniqueIds.size) {
            validation.isValid = false;
            validation.errors.push('存在重复的任务ID');
            validation.statistics.duplicateIds = taskIds.length - uniqueIds.size;
        }
        
        // 检查每个象限的任务顺序
        const quadrantTypes = ['urgent-important', 'important-not-urgent', 'not-important-urgent', 'not-important-not-urgent'];
        
        quadrantTypes.forEach(quadrant => {
            const quadrantTasks = tasks.filter(t => t.quadrant === quadrant);
            validation.statistics.quadrantCounts[quadrant] = quadrantTasks.length;
            
            if (quadrantTasks.length > 0) {
                // 检查顺序是否连续
                const orders = quadrantTasks.map(t => t.order || 0).sort((a, b) => a - b);
                let hasOrderIssue = false;
                
                for (let i = 0; i < orders.length; i++) {
                    if (orders[i] !== i) {
                        hasOrderIssue = true;
                        validation.statistics.orderIssues++;
                        break;
                    }
                }
                
                if (hasOrderIssue) {
                    validation.warnings.push(`象限 ${quadrant} 的任务顺序不连续`);
                }
            }
        });
        
        // 检查必需字段
        tasks.forEach((task, index) => {
            if (!task.id) {
                validation.isValid = false;
                validation.errors.push(`任务 ${index} 缺少ID`);
            }
            if (!task.title || task.title.trim() === '') {
                validation.isValid = false;
                validation.errors.push(`任务 ${task.id || index} 缺少标题`);
            }
            if (!task.quadrant || !quadrantTypes.includes(task.quadrant)) {
                validation.isValid = false;
                validation.errors.push(`任务 ${task.id || index} 象限类型无效`);
            }
        });
        
    } catch (error) {
        validation.isValid = false;
        validation.errors.push(`数据校验过程中发生错误: ${error.message}`);
    }
    
    return validation;
}

/**
 * 修复数据问题
 * @returns {boolean} 是否修复成功
 */
function repairTasksData() {
    console.log('开始修复任务数据...');
    
    try {
        // 移除重复的任务ID
        const seen = new Set();
        tasks = tasks.filter(task => {
            if (seen.has(task.id)) {
                console.warn(`移除重复任务 ID: ${task.id}`);
                return false;
            }
            seen.add(task.id);
            return true;
        });
        
        // 修复每个象限的任务顺序
        const quadrantTypes = ['urgent-important', 'important-not-urgent', 'not-important-urgent', 'not-important-not-urgent'];
        
        quadrantTypes.forEach(quadrant => {
            repairTaskOrder(quadrant);
        });
        
        // 修复缺少的必需字段
        tasks.forEach(task => {
            if (!task.id) {
                task.id = taskIdCounter++;
            }
            if (!task.title || task.title.trim() === '') {
                task.title = '未命名任务';
            }
            if (!task.quadrant || !quadrantTypes.includes(task.quadrant)) {
                task.quadrant = 'not-important-not-urgent';
            }
            if (typeof task.completed !== 'boolean') {
                task.completed = false;
            }
            if (!task.createdAt) {
                task.createdAt = new Date().toLocaleString();
            }
        });
        
        // 保存修复后的数据
        saveTasksToLocalStorage();
        
        console.log('任务数据修复完成');
        return true;
        
    } catch (error) {
        console.error('数据修复失败:', error);
        return false;
    }
}

/**
 * 全局错误处理器
 * @param {Error} error 错误对象
 * @param {string} context 错误上下文
 */
function handleGlobalError(error, context = '未知操作') {
    console.error(`全局错误处理 [${context}]:`, error);
    
    // 记录错误信息
    const errorInfo = {
        timestamp: new Date().toISOString(),
        context: context,
        message: error.message,
        stack: error.stack,
        tasksCount: tasks.length,
        currentQuadrant: getCurrentQuadrantType()
    };
    
    // 尝试数据恢复
    try {
        const validation = validateAllTasksData();
        if (!validation.isValid) {
            console.warn('检测到数据问题，尝试修复...');
            if (repairTasksData()) {
                refreshAllTasks();
                console.log('数据修复成功，界面已刷新');
            }
        }
    } catch (recoveryError) {
        console.error('数据恢复失败:', recoveryError);
        
        // 最后的救命稿草：重新加载页面
        if (confirm('应用出现严重错误，是否重新加载页面？')) {
            window.location.reload();
        }
    }
}

/**
 * 获取当前象限类型（如果在全屏模式中）
 * @returns {string|null} 象限类型
 */
function getCurrentQuadrantType() {
    const fullscreenTasks = document.getElementById('fullscreenTasks');
    return fullscreenTasks ? fullscreenTasks.dataset.quadrantType : null;
}

/**
 * 初始化全局错误监听
 */
function initGlobalErrorHandling() {
    // 捕获JavaScript错误
    window.addEventListener('error', function(event) {
        handleGlobalError(event.error, 'JavaScript运行时错误');
    });
    
    // 捕获Promise拒绝
    window.addEventListener('unhandledrejection', function(event) {
        handleGlobalError(new Error(event.reason), 'Promise拒绝');
    });
    
    console.log('全局错误处理器已初始化');
}

/**
 * 初始化拖拽状态管理
 */
function initDragStateManagement() {
    console.log('初始化拖拽状态管理系统');
    
    // 启动拖拽状态监控
    DragStateManager.setupDragStateMonitoring();
    
    // 添加全局事件监听器
    setupGlobalDragEventListeners();
    
    // 添加页面可见性变化监听
    setupVisibilityChangeHandler();
    
    // 添加窗口焦点变化监听
    setupWindowFocusHandler();
}

/**
 * 设置全局拖拽事件监听器
 */
function setupGlobalDragEventListeners() {
    // 监听所有可能的拖拽结束事件
    document.addEventListener('dragend', function(e) {
        console.log('全局dragend事件触发');
        setTimeout(() => {
            DragStateManager.autoFixDragStates();
        }, 200);
    }, true);
    
    // 监听鼠标释放事件
    document.addEventListener('mouseup', function(e) {
        setTimeout(() => {
            if (DragStateManager.hasRemainingDragStates()) {
                console.log('鼠标释放后检测到残留拖拽状态，执行清理');
                DragStateManager.clearAllDragStates();
            }
        }, 300);
    });
    
    // 监听触摸结束事件（移动设备）
    document.addEventListener('touchend', function(e) {
        setTimeout(() => {
            if (DragStateManager.hasRemainingDragStates()) {
                console.log('触摸结束后检测到残留拖拽状态，执行清理');
                DragStateManager.clearAllDragStates();
            }
        }, 300);
    });
    
    console.log('全局拖拽事件监听器已设置');
}

/**
 * 设置页面可见性变化处理器
 */
function setupVisibilityChangeHandler() {
    document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'visible') {
            // 页面重新可见时清理拖拽状态
            setTimeout(() => {
                console.log('页面重新可见，执行拖拽状态清理');
                DragStateManager.clearAllDragStates();
            }, 100);
        }
    });
}

/**
 * 设置窗口焦点变化处理器
 */
function setupWindowFocusHandler() {
    window.addEventListener('focus', function() {
        // 窗口重新获得焦点时清理拖拽状态
        setTimeout(() => {
            console.log('窗口重新获得焦点，执行拖拽状态清理');
            DragStateManager.clearAllDragStates();
        }, 100);
    });
    
    window.addEventListener('blur', function() {
        // 窗口失去焦点时也清理拖拽状态
        setTimeout(() => {
            DragStateManager.clearAllDragStates();
        }, 100);
    });
}

/**
 * 手动重置拖拽状态（用户可调用的函数）
 */
function manualResetDragState() {
    console.log('手动重置拖拽状态');
    
    // 清理所有拖拽状态
    DragStateManager.clearAllDragStates(true);
    
    // 重新初始化拖拽功能
    setTimeout(() => {
        initDropZones();
        
        // 如果在全屏模式中，也重新初始化
        const fullscreenModal = document.getElementById('fullscreenModal');
        if (fullscreenModal && fullscreenModal.classList.contains('show')) {
            const fullscreenTasks = document.getElementById('fullscreenTasks');
            const quadrantType = fullscreenTasks.dataset.quadrantType;
            if (quadrantType) {
                cleanupFullscreenDragSorting();
                setTimeout(() => {
                    const overlay = document.getElementById('fullscreenModal');
                    if (overlay) {
                        overlay.dataset.quadrant = quadrantType;
                        const modalContainer = overlay.querySelector('.fullscreen-modal');
                        if (modalContainer) {
                            modalContainer.dataset.quadrant = quadrantType;
                        }
                    }
                    fullscreenTasks.dataset.quadrantType = quadrantType;
                    refreshFullscreenTasks();
                }, 100);
            }
        }
        
        console.log('拖拽功能重新初始化完成');
    }, 200);
    
    // 显示重置成功提示
    showTemporaryNotification('拖拽状态已重置', 'success');
}

/**
 * 显示临时通知
 * @param {string} message 通知消息
 * @param {string} type 通知类型（success, warning, error）
 */
function showTemporaryNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `temporary-notification ${type}`;
    
    const colors = {
        success: '#28a745',
        warning: '#ffc107',
        error: '#dc3545',
        info: '#007bff'
    };
    
    notification.innerHTML = `
        <div class="notification-content">
            <span class="notification-icon">${type === 'success' ? '✅' : type === 'warning' ? '⚠️' : type === 'error' ? '❌' : 'ℹ️'}</span>
            <span class="notification-text">${message}</span>
        </div>
    `;
    
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${colors[type]};
        color: white;
        padding: 12px 18px;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        animation: slideInRight 0.3s ease;
        font-size: 14px;
        max-width: 300px;
    `;
    
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
            if (notification.parentNode) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}
